package com.yonyou.ucf.mdf.app.isvdxq.other.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.other.mapper.impl.UnitMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.yonyisv.model.EventContent;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.UnitEnity;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.AccessTokenResponse;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ContentBean;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.UnitBean;
import com.yonyou.ucf.mdf.app.isvdxq.utils.GenericResponse;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.PageBean;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UnitService {
    @Autowired
    private BaseService baseService;
    @Autowired
    private UnitMapperImpl unitMapper;

    public UnitEnity SelectById(Long Id) {
        return unitMapper.selectById(Id);
    }

    public Boolean CheckEntity(Long Id) {
        int rInt = unitMapper.selectCount(Id);
        if (rInt > 0) return true;
        else return false;
    }

    public Integer InsertEntity(UnitEnity entity) {
        return unitMapper.insert(entity);
    }

    public Integer UpdateEntity(UnitEnity entity) {
        return unitMapper.updateByPrimaryKey(entity);
    }

    public List<UnitEnity> SelectAll(String tenantId) {
        return unitMapper.selectAll(tenantId);
    }

    public Integer DeleteById(Long Id) {
        return unitMapper.deleteByPrimaryKey(Id);
    }

    //新增并更新
    public Integer InsertBatch(List<UnitEnity> list) {
        if (list.size() == 0) return 0;
        long start = System.currentTimeMillis();
        int res = unitMapper.insertBatch(list);
        long end = System.currentTimeMillis();
        System.out.println("---------------" + (start - end) + "---------------");
        return res;
    }

    public Integer EventEdit(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        String jsonString = obj.getArchive().replace("detail!id", "detailid").replace("detail!", "");
        UnitBean unitBean = RequestTool.getBean(jsonString, UnitBean.class);
        String unitName = "";
        if (unitBean.getName() != null) {
            unitName = unitBean.getName().getZh_CN();
        }
        UnitEnity unitEnity = RequestTool.getBean(jsonString, UnitEnity.class);
        unitEnity.setUnitName(unitName);
        unitEnity.setTenantId(content.getTenantId());
        System.out.println(JSON.toJSONString(unitEnity));
        Boolean flag = CheckEntity(unitEnity.getId());
        if (flag) {
            int rInt = UpdateEntity(unitEnity);
            return rInt;
        } else {
            int rInt = InsertEntity(unitEnity);
            return rInt;
        }
    }

    public Integer EventDel(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        Long Id = Long.parseLong(obj.getId());
        Boolean flag = CheckEntity(Id);
        if (flag) {
            int rInt = DeleteById(Id);
            return rInt;
        }
        return 0;
    }

    //计量单位批量写入
    public int EventProductUnitEdit(String tenantId, String key, String val) throws IOException {
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return 0;
        int recordCount = 0;
        int curPageIndex = 0;
        boolean flagNext = true;
        while (flagNext) {
            AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
            String token = MyToken.getAccessToken();
            String requrl = gatewayUrl + ApiYon.getUnitList + "?access_token=" + token;
            Map<String, Object> params = new HashMap<>();
            // 除签名外的其他参数
            params.put("pageIndex", String.valueOf(curPageIndex + 1));
            params.put("pageSize", "499");
            if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(val)) {
                params.put("simple", JSONObject.parse("{\"" + key + "\":\"" + val + "\"}"));
            }
            String resString = RequestTool.doPost(requrl, JSONObject.toJSONString(params));
            GenericResponse<PageBean<UnitBean>> response = RequestTool.getBean(resString,
                    new TypeReference<GenericResponse<PageBean<UnitBean>>>() {
                    });
            if (!response.getCode().equals("200")) {
                throw new RuntimeException(resString);
            }
            List<UnitEnity> myDataUnit = new ArrayList<>();
            if (response.getCode().equals("200")) {
                int endPageIndex = response.getData().getEndPageIndex();
                curPageIndex = response.getData().getPageIndex();

                List<UnitBean> resDataUnit = response.getData().getRecordList();
                if (resDataUnit == null || resDataUnit.size() == 0) {
                    flagNext = false;
                    break;
                }
                resDataUnit.forEach(item -> {
                    UnitEnity obj = MyTool.convertBean2Bean(item, UnitEnity.class);
                    obj.setTenantId(tenantId);
                    obj.setUnitName(item.getName().getZh_CN());
                    obj.initData();
                    myDataUnit.add(obj);
                });
                int rIntNew = InsertBatch(myDataUnit);
                recordCount += rIntNew;
                System.out.println("EventProductUnitEdit影响条数" + rIntNew);
                if (endPageIndex <= curPageIndex) flagNext = false;
            }
        }
        return recordCount;
    }


    //计量单位写入
    public int EventProductUnitEditById(String tenantId, String unitId) throws IOException {
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return 0;
        int recordCount = 0;
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String requrl = gatewayUrl + ApiYon.getUnitDetail + "?access_token=" + token;
        Map<String, String> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("id", unitId);
        String resString = RequestTool.doGet(requrl, params);
        GenericResponse<UnitBean> response = RequestTool.getBean(resString,
                new TypeReference<GenericResponse<UnitBean>>() {
                });
        if (!response.getCode().equals("200")) {
            throw new RuntimeException(resString);
        }
        List<UnitEnity> myDataUnit = new ArrayList<>();
        if (response.getCode().equals("200")) {
            UnitBean item = response.getData();
            if (item == null) return 0;
            UnitEnity obj = MyTool.convertBean2Bean(item, UnitEnity.class);
            obj.setTenantId(tenantId);
            obj.setUnitName(item.getName().getZh_CN());
            obj.initData();
            myDataUnit.add(obj);
            int rIntNew = InsertBatch(myDataUnit);
            recordCount += rIntNew;
            System.out.println("EventProductUnitEditById影响条数" + rIntNew);
        }
        return recordCount;
    }
}
